const app = getApp()
var QQMapWX = require('../../libs/qqmap-wx-jssdk.js');
var qqmapsdk;

Page({

  /**
   * 页面的初始数据
   */
  data: {
    nation: '',
    province: '',
    city: '',
    district: '',
    street: '',
    longitude: '',
    latitude: '',
    markers: [],
    region: [],
    detailAddress:"",
    openid:null,
    userInfo:{},
    sex:true
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function () {
    var that=this
    this.getAddress();
    this.getAddressAuthor();
    //获取用户信息
    wx.request({
      url: 'https://www.yujiancs.cn/UserInfo/SelectUser',
      data:{ 
        wxid:app.globalData.openId
      },  method:"POST",
      header: {
        'content-type': 'application/json' // 默认值
      },
      success (res) {
        var sex=true;
          if(res.data[0].Sex=="false"){
            sex=false
          }
          that.setData({
            userInfo:res.data,
            sex:sex
          })
      }
    })
  },
  /**
   *获取高精确地址
   */
  getAddress() {
    var that=this;
    // 实例化腾讯地图API核心类
    qqmapsdk = new QQMapWX({
      key: 'E6YBZ-2HMR2-UCCU7-CLE6Y-NWN6E-WPBQW' // 必填
    })
    //获取当前位置
    wx.getLocation({
      type: 'gcj02',
      success: function (res) {
        //根据坐标获取当前位置名称，显示在顶部，腾讯地图逆地址解析
        console.log(res.latitude);
        console.log(res.longitude);
        qqmapsdk.reverseGeocoder({
          location: {
            latitude: res.latitude,
            longitude: res.longitude
          },
          success: function (addressRes) {
            console.log(addressRes);
            that.setData({
              region:that.data.region.concat(addressRes.result.address_component.province), 
            })
            that.setData({
              region:that.data.region.concat(addressRes.result.address_component.city),
            })
            that.setData({
              region:that.data.region.concat(addressRes.result.address_component.district),
              detailAddress:addressRes.result.address_reference.town.title+addressRes.result.address_reference.street.title+addressRes.result.address_reference.landmark_l2.title
            })
            
            var address = addressRes.result.formatted_addresses.recommend;
            console.log(address);
            //调出地图
            that.getAddressDetail();
          }

        })
      },
    })
  },
  /**
     * 获取地理位置信息详情
     */
    getAddressDetail: function () {
    let that = this;
    wx.getLocation({
      type: 'wgs84',// 参考系
      success: function (res) {
        var latitude = res.latitude;
        var longitude = res.longitude;
        console.log("纬度=" + latitude + " 经度=" + longitude);

        // 构建标注
        var marker = {
          id: 1,
          latitude: latitude,
          longitude: longitude,
          width: 50,
          height: 50
        }
        var markers = new Array();
        markers.push(marker);

        that.setData({ latitude: latitude, longitude: longitude, markers: markers });
        // 构建请求地址
        var qqMapApi = 'https://apis.map.qq.com/ws/geocoder/v1/' + "?location=" + latitude + ',' +
          longitude + "&key=" + 'E6YBZ-2HMR2-UCCU7-CLE6Y-NWN6E-WPBQW' + "&get_poi=1";
      }
    })
  },

  /**
   * 发送请求获取地图接口的返回值
   */
  sendRequest: function (qqMapApi) {
    let that = this;
    // 调用请求
    wx.request({
      url: qqMapApi,
      data: {},
      method: 'GET',
      success: (res) => {
        console.log(res)
        if (res.statusCode == 200 && res.data.status == 0) {
          // 从返回值中提取需要的业务地理信息数据
          that.setData({ nation: res.data.result.address_component.nation });
          that.setData({ province: res.data.result.address_component.province });
          that.setData({ city: res.data.result.address_component.city });
          that.setData({ district: res.data.result.address_component.district });
          that.setData({ street: res.data.result.address_component.street });
        }
      }
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  /**
   * 选择地址
   */
  RegionChange: function (e) {
    this.setData({
      region: e.detail.value
    })
  },
  formSubmit(e){
    wx.showToast({
      title: '提交中...',
      icon:"loading"
    })
    var that=this
    var openId=app.globalData.openId
    wx.getStorage({
      key: 'OpenId',
      complete: (res) => {},
      fail: (res) => {},
      success: (result) => {
        openId=result.data
      },
    })
    wx.request({
      url: 'https://www.yujiancs.cn/UserInfo/UpdateInfo', //仅为示例，并非真实的接口地址
      data: {
        Address:e.detail.value.Area+e.detail.value.Address,
        WxName:e.detail.value.Weixin,
        QQ:e.detail.value.QQ,
        Tel:e.detail.value.Tel,
        Sex:e.detail.value.Sex,
        WxID:openId
      },
      header: {
        'content-type': 'application/json' // 默认值
      },
      success (res) {
        console.log(res.data)
        if(res.data.state==true){
            wx.showToast({
              title: '修改成功！',
              icon:"success"
            })
            wx.navigateBack()
        }
      }
    })
  },
  /**
   * 申请地位权限
   */
  getAddressAuthor(){
  wx.getSetting({
    success: (res) => {
      console.log(JSON.stringify(res))
      // res.authSetting['scope.userLocation'] == undefined    表示 初始化进入该页面
      // res.authSetting['scope.userLocation'] == false    表示 非初始化进入该页面,且未授权
      // res.authSetting['scope.userLocation'] == true    表示 地理位置授权
      if (res.authSetting['scope.userLocation'] != undefined && res.authSetting['scope.userLocation'] != true) {
        wx.showModal({
          title: '请求授权您的位置信息',
          content: '需要获取您的地理位置，请确认授权',
          success: function (res) {
            if (res.cancel) {
              wx.showToast({
                title: '拒绝授权',
                icon: 'none',
                duration: 1000
              })
             wx.switchTab({
               url: '/pages/me/me',
             })
            } else if (res.confirm) {
              wx.openSetting({
                success: function (dataAu) {
                  if (dataAu.authSetting["scope.userLocation"] == true) {
                    wx.showToast({
                      title: '授权成功',
                      icon: 'success',
                      duration: 1000
                    })
                    //再次授权，调用wx.getLocation的API
                    
                  } else {
                    wx.showToast({
                      title: '授权失败',
                      icon: 'none',
                      duration: 1000
                    })
                  }
                }
              })
            }
          }
        })
      } else if (res.authSetting['scope.userLocation'] == undefined) {
        //调用wx.getLocation的API
      }
      else {
        //调用wx.getLocation的API
      }
    }
  })
}

})